/**
 * Created by zhangxiaoyu on 16/12/06.
 */
angular.module('hyt.addWaybillCtrl',[])

  .controller('AddWaybillCtrl',function($scope,$filter,$ionicModal,Storage,AddWaybill,$ionicPopup,PaymentMethod,Sites,$ionicLoading,$timeout,$state,PackType,$cordovaHdoitBle,getPrinter,$ionicPopover,Customers,$window,$stateParams,WayDetailOfOrder,District,Premium,UserByDept){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    var orderId=$stateParams.orderId;
    $scope.waybill={
      info:{
        BELONG_ID:userMsg.rows.baseDeptId, //所属站点，网点
        WAYBILL_NO:'', //承运单号
        WAYBILL_DATE:$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss'), //承运日期
        DEPARTURE_STATION:userMsg.rows.deptName, //始发站
        DESTINATION_ID:'', //到达站
        DESTINATION_STATION:'', //目的站（名称）
        DELIVERY_TYPE:'', //送货方式（0-自提；1-送货；2-上楼）
        WAYBILL_TYPE:'', //运单类型(0-正常承运；1-中转承运；2-外包承运)
        RECEIPT_NUM:'', //回单需要签回的份数
        INSURE_FLAG:'',//是否投保(0是；1否)
        orderId:'',//订单id
        notifyFlag:'0',//是否等通知发货
        userId:'', //业务员
        REMARK:'' //备注
      },
      customerMap:{
        SHIPPER:'', //发货人名称
        SHIPPER_PHONE:'', //发货人电话
        SHIPPER_ADDRESS:'', //发货人地址
        CONSIGNEE:'', //收货人名称
        CONSIGNEE_PHONE:'', //收货人电话
        CONSIGNEE_ADDRESS:'' //收货人地址
      },
      costMap:{
        PICK_UP_COST:'', //提货费
        DECLARE_VALUE:'', //声明价值
        PREMIUM:'', //保费
        PAYMENT_FREIGHT:'', //运费垫付
        DELIVERY_COST:'', //订单送货费
        DROP_OFF:'',//运单送货费
        AGENCY_FUND:'', //代收款
        POINTS:'', //代收款手续费
        PAY_COLLECTION:'', //代收款垫付
        FREIGHT_AMOUNT:'' //运费合计
      },
      payMap:{
        SPOT_PAYMENT:'', //现付
        TO_PAYMENT:'', //到付
        BACK_PAY:'', //欠付
        BACK_TO_PAY:'', //回付
        MONTHLY_BALANCE:'', //月结
        GOODS_TO_CLOCK:'', //货到打卡
        WITHHOLD:'', //代扣
        BACK_NOW:'', //现返
        OWE_TO_RETURN:'', //欠返
        PAYMENT_METHOD:'' //付款方式 0-现付；1-到付；2-欠付；3-回付；4-月结；5-货到打卡；6-代扣；7-多笔付(1至6的付款方式均有值)
      },
      goodsInfo:{
        GOODS_NAME:'', //货物名称
        PIECES:'', //件数
        WEIGHT:'', //重量
        VOLUME:'', //体积
        GOODS_PACK:'' //包装
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };

    //选择承运日期
    $scope.showDate = function() { //选择日期
        var optionsStart = {
            date:new Date(),
            mode: 'date'
        };
        datePicker.show(optionsStart, function(d) {
            if (!isNaN(d.getTime())) {  // valid date
                $scope.$apply(function () {
                    $scope.waybill.info.WAYBILL_DATE = $filter('date')(d,'yyyy-MM-dd');
                });
            }
        });
    };
    //付款方式
    var paymentMethod={
      type:'payment_method',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PaymentMethod.getPaymentMethod(JSON.stringify(paymentMethod));
    $scope.$on('PaymentMethod.Updated', function() {
      var result=PaymentMethod.getResult();
      if (result.success==true){
        $scope.paymentMethods=result.rows;
      }
    });
    //包装方式
    var packType={
      type:'pack_type',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PackType.getPackType(JSON.stringify(packType));
    $scope.$on('PackType.Updated', function() {
      var result=PackType.getResult();
      if (result.success==true){
        $scope.packTypes=result.rows;
      }
    });
    //到达站
    var sites={
      companyId:userMsg.rows.companyId,
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    Sites.getSites(JSON.stringify(sites));
    $scope.$on('Sites.Updated', function() {
      var result=Sites.getResult();
      if (result.success==true){
        $scope.sites=result.rows;
      }
    });
    //订单转承运单
    if (orderId!=''){
      $scope.isOrderWb=1;
      var orderDetail={
        ID:orderId,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      WayDetailOfOrder.getWayDetail(JSON.stringify(orderDetail));
      $scope.$on('WayDetail.Updated', function() {
        var result=WayDetailOfOrder.getResult();
        $scope.waybill.info.orderId=orderId;
        $scope.waybill.customerMap=result.rows.customers;
        $scope.waybill.goodsInfo.GOODS_NAME=result.rows.goods[0].GOODS_NAME;
        $scope.waybill.goodsInfo.PIECES=result.rows.goods[0].PIECES;
        $scope.waybill.goodsInfo.VOLUME=result.rows.goods[0].VOLUME;
        $scope.waybill.goodsInfo.WEIGHT=result.rows.goods[0].WEIGHT;
        $scope.waybill.costMap.AGENCY_FUND=result.rows.waybill.AGENCY_FUND;
        $scope.waybill.costMap.DECLARE_VALUE=result.rows.waybill.DECLARE_VALUE;
        $timeout(function(){
          $("#GOODS_PACK").val(result.rows.goods[0].GOODS_PACK);
          $("#DELIVERY_TYPE").val(result.rows.waybill.DELIVERY_TYPE);
          $("#paymentMethod").val(result.rows.waybill.PAYMENT_METHOD);
          $scope.waybill.costMap.PICK_UP_COST=result.rows.waybill.PICK_UP_COST;
          if ($scope.waybill.costMap.AGENCY_FUND!=undefined){
            feeType=1;
            var points={
              coverage:$scope.waybill.costMap.AGENCY_FUND.toString(),
              type:'1',
              userMsg:{
                username:loginMsg.username,
                password:loginMsg.password,
                uuid:loginMsg.uuid
              }
            };
            if (points.coverage!=''){
              Premium.getPremium(JSON.stringify(points));
            }
          }
        },300);
        if ($scope.waybill.costMap.DECLARE_VALUE!=undefined){
          feeType=0;
          var premium={
            coverage:$scope.waybill.costMap.DECLARE_VALUE.toString(),
            type:'2',
            userMsg:{
              username:loginMsg.username,
              password:loginMsg.password,
              uuid:loginMsg.uuid
            }
          };
          if (premium.coverage!=''){
            Premium.getPremium(JSON.stringify(premium));
          }
        }
        if (result.rows.waybill.PAYMENT_METHOD==7){
          $("#FREIGHT_AMOUNT").removeClass("show").addClass("hide");
          $(".isDisplay").removeClass("hide").addClass("show");
        }else {
          $("#FREIGHT_AMOUNT").removeClass("hide").addClass("show");
          $(".isDisplay").removeClass("show").addClass("hide");
        }
      });
    }else {
      $scope.isOrderWb=0;
    }
    //联系人
    $scope.showloading=true;
    $scope.customersSearch={
      param:{
        createDeptId:userMsg.rows.baseDeptId,
        customerPhone:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    document.onkeydown=function(event){
      if(event.keyCode==13&&$scope.customersSearch.param.customerPhone!=''){
        Customers.getCustomersData($scope.customersSearch);
      }
    };
    var isConsignee;
    $scope.changePhone=function(val,bs) {
      if (val.length == 11) {
        isConsignee=bs;
        $scope.customersSearch.param.customerPhone=val;
        Customers.getCustomersName($scope.customersSearch);
      }
      if (bs==1){
        $scope.waybill.customerMap.CONSIGNEE='';
        $scope.waybill.customerMap.CONSIGNEE_ADDRESS='';
        $('#CONSIGNEE').removeAttr("readonly");
        $('#CONSIGNEE_ADDRESS').removeAttr("readonly");
      }else if (bs==2){
        $scope.waybill.customerMap.SHIPPER='';
        $scope.waybill.customerMap.SHIPPER_ADDRESS='';
        $('#SHIPPER').removeAttr("readonly");
        $('#SHIPPER_ADDRESS').removeAttr("readonly");
      }
    };
    $scope.$on('CustomerName.Updated', function() {
      if (isConsignee==1){
        if (Customers.getNameResult().customerName!=undefined){
          $scope.waybill.customerMap.CONSIGNEE=Customers.getNameResult().customerName;
          $scope.waybill.customerMap.CONSIGNEE_ADDRESS=Customers.getNameResult().customerAddress;
          $('#CONSIGNEE').attr("readonly","readonly");
          $('#CONSIGNEE_ADDRESS').attr("readonly","readonly");
        }
      }else if (isConsignee==2){
        if (Customers.getNameResult().customerName!=undefined){
          $scope.waybill.customerMap.SHIPPER=Customers.getNameResult().customerName;
          $scope.waybill.customerMap.SHIPPER_ADDRESS=Customers.getNameResult().customerAddress;
          $('#SHIPPER').attr("readonly","readonly");
          $('#SHIPPER_ADDRESS').attr("readonly","readonly");
        }
      }
    });
    Customers.getCustomersData($scope.customersSearch);
    $scope.$on('Customers.Updated', function() {
      $scope.customersData=Customers.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      Customers.getCustomersData($scope.customersSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      Customers.getMoreCustomersData($scope.customersSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return Customers.hasNextPage();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/addWaybill/cstConsignee.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modalConsignee = modal;
    });
    $ionicModal.fromTemplateUrl('templates/tab-workbench/addWaybill/cstShipper.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modalShipper = modal;
    });
    $scope.chooseConsignee=function(customerName,customerPhone,customerAddress){
      $scope.waybill.customerMap.CONSIGNEE=customerName;
      $scope.waybill.customerMap.CONSIGNEE_PHONE=customerPhone;
      $scope.waybill.customerMap.CONSIGNEE_ADDRESS=customerAddress;
      $('#CONSIGNEE').attr("readonly","readonly");
      $('#CONSIGNEE_ADDRESS').attr("readonly","readonly");
      $scope.modalConsignee.hide();
    };
    $scope.chooseShipper=function(customerName,customerPhone,customerAddress){
      $scope.waybill.customerMap.SHIPPER=customerName;
      $scope.waybill.customerMap.SHIPPER_PHONE=customerPhone;
      $scope.waybill.customerMap.SHIPPER_ADDRESS=customerAddress;
      $('#SHIPPER').attr("readonly","readonly");
      $('#SHIPPER_ADDRESS').attr("readonly","readonly");
      $scope.modalShipper.hide();
    };
    //省市区
    //var gpsProvince=Storage.get('gpsProvince');
    //var gpsCity=Storage.get('gpsCity');
    //var gpsArea=Storage.get('gpsArea');
    //var isGps=true;
    //var province={
    //  type:"province",
    //  userMsg:{
    //    username:loginMsg.username,
    //    password:loginMsg.password,
    //    uuid:loginMsg.uuid
    //  }
    //};
    //var district={
    //  type:"",
    //  parentId:'',
    //  userMsg:{
    //    username:loginMsg.username,
    //    password:loginMsg.password,
    //    uuid:loginMsg.uuid
    //  }
    //};
    //District.getProvince(JSON.stringify(province));
    //$("#provinceF").change(function(e) {
    //  isGps=false;
    //  if ($('#provinceF').val()=='地区选择'){
    //    $scope.cityDataF=null;
    //    $scope.areaDataF=null;
    //  }else {
    //    district.parentId=$('#provinceF').val();
    //    District.getCityF(JSON.stringify(district));
    //  }
    //});
    //$("#cityF").change(function(e) {
    //  isGps=false;
    //  district.parentId=$('#cityF').val();
    //  District.getAreaF(JSON.stringify(district));
    //});
    //$("#provinceS").change(function(e) {
    //  if ($('#provinceS').val()=='地区选择'){
    //    $scope.cityDataS=null;
    //    $scope.areaDataS=null;
    //  }else {
    //    district.parentId=$('#provinceS').val();
    //    District.getCityS(JSON.stringify(district));
    //  }
    //});
    //$("#cityS").change(function(e) {
    //  district.parentId=$('#cityS').val();
    //  District.getAreaS(JSON.stringify(district));
    //});
    //$scope.$on('Province.Updated', function() {
    //  $scope.provinceData=District.getPro().rows;
    //  if (isGps==true){
    //    $timeout(function(){
    //      $('#provinceF option:contains(' + gpsProvince + ')').each(function(){
    //        if ($(this).text() == gpsProvince) {
    //          $(this).attr('selected', true);
    //          district.parentId=$('#provinceF').val();
    //          District.getCityF(JSON.stringify(district));
    //        }
    //      });
    //    },100);
    //  }
    //});
    //$scope.$on('CityF.Updated', function() {
    //  $scope.cityDataF=District.getCitF().rows;
    //  if (isGps==false){
    //    district.parentId=$scope.cityDataF[0].id;
    //    District.getAreaF(JSON.stringify(district));
    //  }else {
    //    $timeout(function(){
    //      $('#cityF option:contains(' + gpsCity + ')').each(function(){
    //        if ($(this).text() == gpsCity) {
    //          $(this).attr('selected', true);
    //          district.parentId=$('#cityF').val();
    //          District.getAreaF(JSON.stringify(district));
    //        }
    //      });
    //    },100);
    //  }
    //});
    //$scope.$on('AreaF.Updated', function() {
    //  $scope.areaDataF=District.getAreF().rows;
    //  if (isGps==true){
    //    $timeout(function(){
    //      $('#areaF option:contains(' + gpsArea + ')').each(function(){
    //        if ($(this).text() == gpsArea) {
    //          $(this).attr('selected', true);
    //        }
    //      });
    //    },100);
    //  }
    //});
    //$scope.$on('CityS.Updated', function() {
    //  $scope.cityDataS=District.getCitS().rows;
    //  district.parentId=$scope.cityDataS[0].id;
    //  District.getAreaS(JSON.stringify(district));
    //});
    //$scope.$on('AreaS.Updated', function() {
    //  $scope.areaDataS=District.getAreS().rows;
    //});

    $("#paymentMethod").change(function(e){
      var paymentMethod=$("#paymentMethod option:selected").val();
      if (paymentMethod==7){
        $("#FREIGHT_AMOUNT").removeClass("show").addClass("hide");
        $(".isDisplay").removeClass("hide").addClass("show");
      }else {
        $("#FREIGHT_AMOUNT").removeClass("hide").addClass("show");
        $(".isDisplay").removeClass("show").addClass("hide");
      }
    });
    //保费自动生成
    var feeType;
    $("#DECLARE_VALUE").on("blur",function(){
      feeType=0;
      var premium={
        coverage:$(this).val(),
        type:'2',
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      if (premium.coverage!=''){
        Premium.getPremium(JSON.stringify(premium));
      }
    });
    $scope.$on('Premium.Updated', function() {
      if(Premium.getResult().rows.rate!=-1){
        if (feeType==0){
          $("#PREMIUM").val(parseFloat(Premium.getResult().rows.rate).toFixed(2));
        }else if (feeType==1){
          $("#POINTS").val(parseFloat(Premium.getResult().rows.rate).toFixed(2));
        }
      }else {
        if (feeType==0){
          $("#PREMIUM").val('');
        }else if (feeType==1){
          $("#POINTS").val('');
        }
      }
    });
    //代收款手续费自动生成
    $("#AGENCY_FUND").on("blur",function(){
      feeType=1;
      var points={
        coverage:$(this).val(),
        type:'1',
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      if (points.coverage!=''){
        Premium.getPremium(JSON.stringify(points));
      }
    });
    $(".twoDot").on("blur",function(){
      $(this).val(parseFloat($(this).val()).toFixed(2));
    });
    //业务员
    var userByDept={
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    UserByDept.getUserByDept(JSON.stringify(userByDept));
    $scope.$on('UserByDept.Updated', function() {
      var result=UserByDept.getResult();
      if (result.success==true){
        $scope.userDepts=result.rows;
      }
    });
    //保存承运单
    var isButton;
    function  addWaybill(){
      //字段赋值
      $scope.waybill.info.DESTINATION_ID=$("#site option:selected").val();
      $scope.waybill.goodsInfo.GOODS_PACK=$("#GOODS_PACK option:selected").val();
      $scope.waybill.info.DELIVERY_TYPE=$("#DELIVERY_TYPE option:selected").val();
      $scope.waybill.payMap.PAYMENT_METHOD=$("#paymentMethod option:selected").val();
      $scope.waybill.info.userId=$("#userDept option:selected").val();
      $scope.waybill.info.WAYBILL_NO=$('#WAYBILL_NO').val();
      $scope.waybill.goodsInfo.WEIGHT=$('#WEIGHT').val();
      $scope.waybill.goodsInfo.VOLUME=$('#VOLUME').val();
      $scope.waybill.costMap.FREIGHT_AMOUNT=$("#FREIGHT_AMOUNT").find("input").val();
      $scope.waybill.payMap.SPOT_PAYMENT=$("#SPOT_PAYMENT").val();
      $scope.waybill.payMap.TO_PAYMENT=$("#TO_PAYMENT").val();
      $scope.waybill.payMap.BACK_PAY=$("#BACK_PAY").val();
      $scope.waybill.payMap.BACK_TO_PAY=$("#BACK_TO_PAY").val();
      $scope.waybill.payMap.MONTHLY_BALANCE=$("#MONTHLY_BALANCE").val();
      $scope.waybill.payMap.GOODS_TO_CLOCK=$("#GOODS_TO_CLOCK").val();
      $scope.waybill.payMap.WITHHOLD=$("#WITHHOLD").val();
      $scope.waybill.payMap.BACK_NOW=$("#BACK_NOW").val();
      $scope.waybill.payMap.OWE_TO_RETURN=$("#OWE_TO_RETURN").val();
      $scope.waybill.costMap.PICK_UP_COST=$("#PICK_UP_COST").val();
      $scope.waybill.costMap.DROP_OFF=$("#DROP_OFF").val();
      $scope.waybill.costMap.DECLARE_VALUE=$("#DECLARE_VALUE").val();
      $scope.waybill.costMap.PREMIUM=$("#PREMIUM").val();
      $scope.waybill.costMap.PAYMENT_FREIGHT=$("#freightAdv").find("input").val();
      $scope.waybill.costMap.AGENCY_FUND=$("#AGENCY_FUND").val();
      $scope.waybill.costMap.POINTS=$("#POINTS").val();
      $scope.waybill.costMap.PAY_COLLECTION=$("#agenFdAdv").find("input").val();
      //判断运单类型
      if ($scope.waybill.info.DESTINATION_ID!=''&&$scope.waybill.info.DESTINATION_STATION==''){
        $scope.waybill.info.WAYBILL_TYPE='0';
      }else if ($scope.waybill.info.DESTINATION_ID!=''&&$scope.waybill.info.DESTINATION_STATION!=''){
        $scope.waybill.info.WAYBILL_TYPE='1';
      }else if ($scope.waybill.info.DESTINATION_ID==''&&$scope.waybill.info.DESTINATION_STATION!=''){
        $scope.waybill.info.WAYBILL_TYPE='2';
      }
      //判断付款方式
      var paymentMethod=$("#paymentMethod option:selected").val();
      if (paymentMethod==0){
        $scope.waybill.payMap.SPOT_PAYMENT=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==1){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==2){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==3){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==4){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==5){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY=$scope.waybill.costMap.FREIGHT_AMOUNT;
        $scope.waybill.payMap.WITHHOLD='';
      }else if (paymentMethod==6){
        $scope.waybill.payMap.SPOT_PAYMENT='';
        $scope.waybill.payMap.TO_PAYMENT='';
        $scope.waybill.payMap.BACK_TO_PAY='';
        $scope.waybill.payMap.MONTHLY_BALANCE='';
        $scope.waybill.payMap.GOODS_TO_CLOCK='';
        $scope.waybill.payMap.BACK_PAY='';
        $scope.waybill.payMap.WITHHOLD=$scope.waybill.costMap.FREIGHT_AMOUNT;
      }else if (paymentMethod==7){
        $scope.waybill.costMap.FREIGHT_AMOUNT=0;
        if ($scope.waybill.payMap.SPOT_PAYMENT!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.SPOT_PAYMENT);
        }
        if ($scope.waybill.payMap.TO_PAYMENT!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.TO_PAYMENT);
        }
        if ($scope.waybill.payMap.BACK_TO_PAY!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.BACK_TO_PAY);
        }
        if ($scope.waybill.payMap.MONTHLY_BALANCE!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.MONTHLY_BALANCE);
        }
        if ($scope.waybill.payMap.GOODS_TO_CLOCK!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.GOODS_TO_CLOCK);
        }
        if ($scope.waybill.payMap.BACK_PAY!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.BACK_PAY);
        }
        if ($scope.waybill.payMap.WITHHOLD!=''){
          $scope.waybill.costMap.FREIGHT_AMOUNT=$scope.waybill.costMap.FREIGHT_AMOUNT+parseFloat($scope.waybill.payMap.WITHHOLD);
        }
        $scope.waybill.costMap.FREIGHT_AMOUNT=parseFloat($scope.waybill.costMap.FREIGHT_AMOUNT).toFixed(2);
      }
      if ($scope.waybill.costMap.DECLARE_VALUE!=''){
        $scope.waybill.info.INSURE_FLAG='0';
      }else {
        $scope.waybill.info.INSURE_FLAG='1';
      }
      var WITHHOLD,AGENCY_FUND,POINTS,PAY_COLLECTION;
      if ($scope.waybill.payMap.WITHHOLD==''){
        WITHHOLD=0;
      }else {
        WITHHOLD=$scope.waybill.payMap.WITHHOLD;
      }
      if ($scope.waybill.costMap.AGENCY_FUND==''){
        AGENCY_FUND=0;
      }else {
        AGENCY_FUND=$scope.waybill.costMap.AGENCY_FUND;
      }
      if ($scope.waybill.costMap.POINTS==''){
        POINTS=0;
      }else {
        POINTS=$scope.waybill.costMap.POINTS;
      }
      if ($scope.waybill.costMap.PAY_COLLECTION==''){
        PAY_COLLECTION=0;
      }else {
        PAY_COLLECTION=$scope.waybill.costMap.PAY_COLLECTION;
      }
      //if ($scope.isOrderWb==1){
      //  $scope.waybill.costMap.DELIVERY_COST=$scope.waybill.costMap.DROP_OFF;
      //  $scope.waybill.costMap.DROP_OFF='';
      //}
      if($scope.waybill.info.DESTINATION_ID==''&&($scope.waybill.info.DESTINATION_STATION==''||$scope.waybill.info.DESTINATION_STATION==null)) {
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择到达站或输入目的地",
          duration: 1500
        });
        $timeout(function(){
          $("#site").focus();
        },160);
      }else if($scope.waybill.customerMap.CONSIGNEE_PHONE==''||$scope.waybill.customerMap.CONSIGNEE_PHONE==null) {
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入收货人电话",
          duration: 1500
        });
        $timeout(function(){
          $("#CONSIGNEE_PHONE").focus();
        },160);
      }else if ($scope.waybill.customerMap.CONSIGNEE==''||$scope.waybill.customerMap.CONSIGNEE==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入收货人姓名",
          duration: 1500
        });
        $timeout(function(){
          $("#CONSIGNEE").focus();
        },160);
      }else if($scope.waybill.customerMap.SHIPPER_PHONE==''||$scope.waybill.customerMap.SHIPPER_PHONE==null) {
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入发货人电话",
          duration: 1500
        });
        $timeout(function(){
          $("#SHIPPER_PHONE").focus();
        },160);
      }else if ($scope.waybill.customerMap.SHIPPER==''||$scope.waybill.customerMap.SHIPPER==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入发货人姓名",
          duration: 1500
        });
        $timeout(function(){
          $("#SHIPPER").focus();
        },160);
      }else if ($scope.waybill.goodsInfo.GOODS_NAME==''||$scope.waybill.goodsInfo.GOODS_NAME==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入货物名称",
          duration: 1500
        });
        $timeout(function(){
          $("#GOODS_NAME").focus();
        },160);
      }else if ($scope.waybill.goodsInfo.PIECES==''||$scope.waybill.goodsInfo.PIECES==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请输入货物数量",
          duration: 1500
        });
        $timeout(function(){
          $("#PIECES").focus();
        },160);
      }else if(!(/^1[34578]\d{9}$/.test($scope.waybill.customerMap.CONSIGNEE_PHONE))){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请正确输入收货人电话",
          duration: 1500
        });
        $timeout(function(){
          $("#CONSIGNEE_PHONE").focus();
        },160);
      }else if(!(/^1[34578]\d{9}$/.test($scope.waybill.customerMap.SHIPPER_PHONE))){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请正确输入发货人电话",
          duration: 1500
        });
        $timeout(function(){
          $("#SHIPPER_PHONE").focus();
        },160);
      }else if ($scope.waybill.info.userId==''||$scope.waybill.info.userId==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择业务员",
          duration: 1500
        });
        $timeout(function(){
          $("#userDept").focus();
        },160);
      }else if (parseFloat(PAY_COLLECTION)+parseFloat(POINTS)+parseFloat(WITHHOLD)>AGENCY_FUND){
        $ionicLoading.show({
          noBackdrop: true,
          template: "代扣+代收款垫付+货款手续费之和不能大于代收款",
          duration: 1500
        });
      }else {
        if ($scope.waybill.costMap.FREIGHT_AMOUNT==''||$scope.waybill.costMap.FREIGHT_AMOUNT==null){
          var confirmPopup = $ionicPopup.confirm({
            title: '未填写运费项',
            okText:'确定',
            cancelText:'取消'
          });
        }else {
          var confirmPopup = $ionicPopup.confirm({
            title: "运费合计为:"+parseFloat($scope.waybill.costMap.FREIGHT_AMOUNT).toFixed(2)+'元',
            okText:'确定',
            cancelText:'取消'
          });
        }
        confirmPopup.then(function(res) {
          if(res) {
            if ($scope.waybill.costMap.FREIGHT_AMOUNT==0){
              $scope.waybill.costMap.FREIGHT_AMOUNT='';
            }
            console.log($scope.waybill);
            AddWaybill.getWaybill(JSON.stringify($scope.waybill));
          } else {
            return false;
          }
        });
      }
    }
    $scope.$on('AddWaybill.Updated', function() {
      var result=AddWaybill.getResult();
      if (isButton==0){
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存成功",
            duration: 1500
          });
          $state.go('tab.workbench');
        }else if (result.msg=='0001'){
          $ionicLoading.show({
            noBackdrop: true,
            template: "该运单号已存在",
            duration: 1500
          });
        }
      }else if (isButton==1){
        waybillNum=result.waybillNo;
        wayId=result.wayId;
        destinationPhone=result.deptPhone;
        if (result.success==true){
          $scope.popover.show(eventPrint);
          var printMsg={
            deptId:userMsg.rows.baseDeptId,
            userMsg:{
              username:loginMsg.username,
              password:loginMsg.password,
              uuid:loginMsg.uuid
            }
          };
          getPrinter.getPrintSet(JSON.stringify(printMsg));
        }else if (result.msg=='0001'){
          $ionicLoading.show({
            noBackdrop: true,
            template: "该运单号已存在",
            duration: 1500
          });
        }
      }
    });
    $scope.saveWaybill=function(){
      isButton=0;
      addWaybill();
    };
    //打印
    $ionicPopover.fromTemplateUrl('templates/tab-workbench/addWaybill/printConfirm.html', {
      scope: $scope
    }).then(function(popover) {
      $scope.popover = popover;
    });
    //添加打印机
    $scope.scanBluetooth=function(){
      $cordovaHdoitBle.scan();
    };
    $scope.bluetooth='未连接蓝牙设备';
    var timer=window.setInterval(getBleName,1000);
    var waybillNum,destinationPhone,eventPrint,wayId;
    $scope.printWaybill=function($event){
      isButton=1;
      eventPrint=$event;
      addWaybill();
      $scope.$on('GetPrint.Updated', function() {
        $scope.printsMsg = getPrinter.getResult().rows;
        if ($scope.printsMsg.goods_flag==1){
          if ($scope.printsMsg.print_behave==1&&$scope.waybill.goodsInfo.PIECES!=''){
            $scope.printsMsg.goods_pieces=$scope.waybill.goodsInfo.PIECES;
            $('#goodsPieces').attr("readonly",true);
          }else if ($scope.printsMsg.print_behave==1&&$scope.waybill.goodsInfo.PIECES==''){
            $scope.printsMsg.goods_pieces=1;
            $('#goodsPieces').attr("readonly",true);
          }else if($scope.printsMsg.print_behave==0){
            $('#goodsPieces').focus();
          }
        }else {
          $('#goodsPieces').attr("readonly",true);
        }
        if ($scope.printsMsg.company_name==null){
          $scope.printsMsg.company_name='存根标题';
        }
        if ($scope.printsMsg.phone==null){
          $scope.printsMsg.phone='客服电话';
        }
        if ($scope.printsMsg.remark==null){
          $scope.printsMsg.remark='责任条文';
        }
      });
    };
    $scope.$on('$destroy', function() {
      $scope.popover.remove();
    });
    $scope.confirmPrint=function(){
      if ($scope.bluetooth=='未连接蓝牙设备'){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请先连接打印机",
          duration: 1500
        });
      }else {
        if ($scope.printsMsg.company_flag==1){
          readyToPrintStub(0);
        }
        if ($scope.printsMsg.shipper_flag==1){
          readyToPrintStub(1);
        }
        if ($scope.printsMsg.goods_flag==1){
          for (var i=0;i<$scope.printsMsg.goods_pieces;i++){
            readyToPrintGoods();
          }
        }
        $scope.popover.remove();
        $ionicLoading.show({
          noBackdrop: true,
          template: "保存成功",
          duration: 1500
        });
        $state.go('tab.workbench');
      }
    };
    $scope.cancelPrint=function(){
      $scope.popover.remove();
      $ionicLoading.show({
        noBackdrop: true,
        template: "保存成功",
        duration: 1500
      });
      $state.go('tab.workbench');
    };
    function getBleName(){
      //蓝牙设备名称
      $cordovaHdoitBle.bluetoothName(function(success){
        if(success!=null){
          $scope.bluetooth=success+'已连接';
          $('#refresh').focus();
          window.clearInterval(timer);
        }
        else {
          $scope.bluetooth='未连接蓝牙设备';
        }
      },function(err){
        $scope.bluetooth='未连接蓝牙设备';
      });
    }
    function readyToPrintStub(i){
      var line;
      if ($("#site option:selected").val()!=''&&$scope.waybill.info.DESTINATION_STATION!=''){
        line=userMsg.rows.deptName+" → "+$("#site option:selected").text()+" → "+$scope.waybill.info.DESTINATION_STATION;
      }else if ($("#site option:selected").val()!=''&&$scope.waybill.info.DESTINATION_STATION==''){
        line=userMsg.rows.deptName+" → "+$("#site option:selected").text();
      }else if ($("#site option:selected").val()==''&&$scope.waybill.info.DESTINATION_STATION!=''){
        line=userMsg.rows.deptName+" → "+$scope.waybill.info.DESTINATION_STATION;
      }
      //设置打印机页面
      var startPageOption = {"pageWidth":600,"pageHeight":400};
      $cordovaHdoitBle.startPageZhike(startPageOption);
      //打印文本
      var companyNmae = {"x":10,"y":5,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.company_name,companyNmae);

      var waybillNO={"x":10,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("运单号:",waybillNO);

      var waybillNOTxt={"x":110,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike(waybillNum,waybillNOTxt);

      var date={"x":330,"y":65,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($filter('date')(new Date($scope.waybill.info.WAYBILL_DATE),'yyyy-MM-dd'),date);

      var phone={"x":420,"y":17.5,"textSize":2,"fontName":"斜体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.phone,phone);

      if (i==0){
        var companyStub={"x":490,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike("存根",companyStub);
      }else if(i==1){
        var shipperStub={"x":460,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike("发货方留存",shipperStub);
      }

      //线路及货物信息
      var lineAndGoods={"x":10,"y":105,"textSize":15,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike(line,lineAndGoods);

      //送货方式
      var deliveryType={"x":380,"y":145,"textSize":3,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($("#DELIVERY_TYPE option:selected").text(),deliveryType);

      //收货人
      var consignee={"x":10,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("收货方",consignee);

      //收货人名称
      var consigneeName={"x":110,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybill.customerMap.CONSIGNEE.substring(0,4),consigneeName);

      //收货人电话
      var consigneePhone={"x":210,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybill.customerMap.CONSIGNEE_PHONE,consigneePhone);

      //发货人
      var shipper={"x":10,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("发货方",shipper);

      //发货人名称
      var shipperName={"x":110,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybill.customerMap.SHIPPER.substring(0,4),shipperName);

      //发货人电话
      var shipperPhone={"x":210,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybill.customerMap.SHIPPER_PHONE,shipperPhone);

      //代收、代收垫付
      var collection={"x":10,"y":215,"textSize":4,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike('代收:'+$scope.waybill.costMap.AGENCY_FUND+' '+'代收垫付:'+$scope.waybill.costMap.PAY_COLLECTION,collection);

      //运费、运费垫付
      var freight={"x":10,"y":245,"textSize":4,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike('运费:'+$scope.waybill.costMap.FREIGHT_AMOUNT+' '+'运费垫付:'+$scope.waybill.costMap.PAYMENT_FREIGHT,freight);

      //信息费
      var informationFee={"x":10,"y":285,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike('现返:'+$scope.waybill.payMap.BACK_NOW+' '+'欠返:'+$scope.waybill.payMap.OWE_TO_RETURN,informationFee);

      //到站信息
      if ($("#site option:selected").text()!=''){
        var destinationNote={"x":10,"y":315,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike($("#site option:selected").text()+'  '+destinationPhone,destinationNote);
      }

      //备注
      var remark={"x":10,"y":345,"width":520,"height":64,"fontSize":2,"rotate":0,"bold":1,"underline":false,"reverse":false};
      $cordovaHdoitBle.multilineText($scope.printsMsg.remark,remark);

      //开票人
      var drawer={"x":380,"y":315,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("开票人:"+userMsg.rows.cname,drawer);

      //扫码跟踪
      var tracking={"x":470,"y":215,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("扫码跟踪",tracking);

      //打印二维码
      var QRCode = {"x":450,"y":90,"size":3};
      $cordovaHdoitBle.printQRcodeZhike("http://www.xyt56.net/html/scanning.html?wayId="+wayId,QRCode);
      $cordovaHdoitBle.doPrint();
      $cordovaHdoitBle.gotoMarklabel();
    }
    function readyToPrintGoods(){
      var line;
      if ($("#site option:selected").val()!=''&&$scope.waybill.info.DESTINATION_STATION!=''){
        line=userMsg.rows.deptName+" → "+$("#site option:selected").text()+" → "+$scope.waybill.info.DESTINATION_STATION;
      }else if ($("#site option:selected").val()!=''&&$scope.waybill.info.DESTINATION_STATION==''){
        line=userMsg.rows.deptName+" → "+$("#site option:selected").text();
      }else if ($("#site option:selected").val()==''&&$scope.waybill.info.DESTINATION_STATION!=''){
        line=userMsg.rows.deptName+" → "+$scope.waybill.info.DESTINATION_STATION;
      }
      //设置打印机页面
      var startPageOption = {"pageWidth":600,"pageHeight":430};
      $cordovaHdoitBle.startPageZhike(startPageOption);
      //打印文本
      var companyNmae = {"x":10,"y":-5,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.company_name,companyNmae);

      var phone={"x":420,"y":7.5,"textSize":2,"fontName":"斜体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.phone,phone);

      //运单号
      var waybillNO={"x":10,"y":80,"textSize":20,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike(waybillNum,waybillNO);

      //线路
      var lines={"x":10,"y":160,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike(line,lines);

      //打印一维码
      var oneCode = {"x":10,"y":280,"type":'128','width':1,'height':85,'rotate':false};
      $cordovaHdoitBle.printBarcodeZhike(waybillNum,oneCode);

      var massage={"x":10,"y":380,"textSize":1,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike(waybillNum+'  '+$scope.waybill.info.WAYBILL_DATE,massage);

      $cordovaHdoitBle.doPrint();
      $cordovaHdoitBle.gotoMarklabel();
    }
    //添加费用项
    $scope.items= [{index:1,name:'现返/欠返'},{index:2,name:'运费垫付'}, {index:3,name:'代收款'},{index:4,name:'代收款垫付'}];
    var popupForWarehouse;
    $scope.addCost=function(){
      popupForWarehouse = $ionicPopup.alert({
        template: '<div class="list">                '+
        '  <ion-item ng-repeat="item in items" ng-click="removeCost($index,item.index)" class="item item-icon-right"> '+
        '    <h2 >{{item.name}}<h2>                   '+
        '  </ion-item>                                      '+
        '</div>                                      ',
        title:'请选择需要添加的费用',
        scope: $scope,
        okText:'取消'
      });
    };
    $scope.removeCost= function (r,i) {
      $scope.items.splice(r,1);
      switch(i) {
        case 1:
          $("#nowOwe").removeClass("hide").addClass("show");
          break;
        case 2:
          $("#freightAdv").removeClass("hide").addClass("show");
          break;
        case 3:
          $("#agencyFund").removeClass("hide").addClass("show");
          break;
        case 4:
          $("#agenFdAdv").removeClass("hide").addClass("show");
          break;
        default:
          break;
      }
      popupForWarehouse.close();
    };
    $scope.holdOnRemove=function(i){
      var receipt = $ionicPopup.confirm({
        title : '是否移除此费用项',
        cancelText : '否',
        cancelType : 'button-stable',
        okText : '是'
      });
      receipt.then(function(r){
        if(r){
          switch(i) {
            case 1:
              $("#nowOwe").removeClass("show").addClass("hide");
              $scope.items.splice(0,0,{index:1,name:'现返/欠返'});
              $scope.waybill.payMap.BACK_NOW='';
              $scope.waybill.payMap.OWE_TO_RETURN='';
              break;
            case 2:
              $("#freightAdv").removeClass("show").addClass("hide");
              if ($scope.items.length!=0){
                if ($scope.items[0].index==1){
                  $scope.items.splice(1,0,{index:2,name:'运费垫付'});
                }else {
                  $scope.items.splice(0,0,{index:2,name:'运费垫付'});
                }
              }else {
                $scope.items.splice(0,0,{index:2,name:'运费垫付'});
              }
              $scope.waybill.costMap.PAYMENT_FREIGHT='';
              break;
            case 3:
              $("#agencyFund").removeClass("show").addClass("hide");
              if ($scope.items.length!=0){
                if ($scope.items[0].index==1&&$scope.items[1].index==2){
                  $scope.items.splice(2,0,{index:3,name:'代收款'});
                }else if ($scope.items[0].index==1||$scope.items[0].index==2){
                  $scope.items.splice(1,0,{index:3,name:'代收款'});
                }else {
                  $scope.items.splice(0,0,{index:3,name:'代收款'});
                }
              }else {
                $scope.items.splice(0,0,{index:3,name:'代收款'});
              }
              $scope.waybill.costMap.AGENCY_FUND='';
              break;
            case 4:
              $("#agenFdAdv").removeClass("show").addClass("hide");
              $scope.items.splice(3,0,{index:4,name:'代收款垫付'});
              $scope.waybill.costMap.PAY_COLLECTION='';
              break;
            default:
              break;
          }
        }else{
          console.log('取消');
        }
      });
    };
    $scope.callPhone = function (mobilePhone) {
      var confirmPopup = $ionicPopup.confirm({
        title:mobilePhone,
        okText:'呼叫',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if (res) {
          $window.location.href = "tel:" + mobilePhone;
        }else {

        }
      });
    };
  });
